package com.study.happystudy.controller;

import com.study.happystudy.entity.ResultEntity;
import com.study.happystudy.po.*;
import com.study.happystudy.service.impl.ExamPaperServiceImpl;
import com.study.happystudy.service.impl.MessageServiceImpl;
import com.study.happystudy.service.impl.QuestionServiceImpl;
import com.study.happystudy.service.impl.UserMistakeServiceImpl;
import com.study.happystudy.tool.ColorChange;
import jakarta.annotation.Resource;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@CrossOrigin
@RequestMapping("question/")
public class QuestionController {

    /*
    list:
        1. 新建题目
        2. 根据id返回题目
        3. 根据科目id获取所有题目
        4. 根据id删除题目
        5. 根据题目类型筛选
        6. 根据科目id和题目类型筛选
        7. 加入错题
        8. 移除错题
        9. 获取错题(uid,sid)
    */
    @Resource
    QuestionServiceImpl qsi;

    @Resource
    UserMistakeServiceImpl umi;

    @Resource
    ExamPaperServiceImpl examPaperService;
    @Resource
    MessageServiceImpl ms;

    /**
     * 新建题目
     *
     * @param questionType  题目类型
     * @param score         分值
     * @param description   题目描述
     * @param options       题目选项
     * @param correctAnswer 正确答案
     * @param subjectId     科目ID
     * @return JSON
     */
    @PostMapping("addQuestion")
    public String addQuestion(
            @RequestParam("questionType") String questionType,
            @RequestParam("score") int score,
            @RequestParam("description") String description,
            @RequestParam("options") String options,
            @RequestParam("correctAnswer") String correctAnswer,
            @RequestParam("subjectId") int subjectId,
            @RequestParam("analysis") String analysis) {
        int result = qsi.addQuestion(questionType, score, description, options, correctAnswer, subjectId, analysis);
        if (result > 0) {
            return ResultEntity.Success(result);
        } else {
            return ResultEntity.Fail(result, "新建题目失败");
        }
    }

    /**
     * 根据ID获取题目
     *
     * @param questionId 题目ID
     * @return JSON
     */
    @GetMapping("getQuestionById")
    public Question getQuestionById(@Param("questionId") Integer questionId) {
        return qsi.getQuestionById(questionId);
    }

    /**
     * 根据科目ID获取所有题目
     *
     * @param subjectId 科目ID
     * @return JSON
     */
    @GetMapping("getQuestionsBySubjectId")
    public List<Question> getQuestionsBySubjectId(@Param("subjectId") int subjectId) {
        return qsi.getQuestionsBySubjectId(subjectId);
    }

    /**
     * 根据ID删除题目
     *
     * @param questionId 题目ID
     * @return JSON
     */
    @DeleteMapping("deleteQuestionById")
    public String deleteQuestionById(@Param("questionId") int questionId) {
        int result = qsi.deleteQuestionById(questionId);
        if (result > 0) {
            return ResultEntity.Success();
        } else {
            return ResultEntity.Fail(result, "删除题目失败");
        }
    }

    /**
     * 根据题目类型筛选题目
     *
     * @param questionType 题目类型
     * @return JSON
     */
    @GetMapping("getQuestionsByType")
    public List<Question> getQuestionsByType(@Param("questionType") String questionType) {
        return qsi.getQuestionsByType(questionType);
    }

    /**
     * 根据科目ID和题目类型筛选题目
     *
     * @param subjectId    科目ID
     * @param questionType 题目类型
     * @return JSON
     */
    @GetMapping("getQuestionsBySubjectIdAndType")
    public List<Question> getQuestionsBySubjectIdAndType(
            @Param("subjectId") int subjectId,
            @Param("questionType") String questionType) {

        if (subjectId == -1) {
            return qsi.getQuestionsByType(questionType);
        }
        if (questionType == "") {
            return qsi.getQuestionsBySubjectId(subjectId);
        }

        return qsi.getQuestionsBySubjectIdAndType(subjectId, questionType);
    }

    /**
     * 加入错题
     *
     * @param userId     用户ID
     * @param questionId 题目ID
     * @return JSON
     * todo: 没判断题目/用户是否存在，待完善(剩下的都是)
     */
    @PostMapping("addMistake")
    public String addMistake(
            @RequestParam("userId") int userId,
            @RequestParam("questionId") int questionId
    ) {
        umi.addMistake(userId, questionId);
        return ResultEntity.Success();
    }

    @DeleteMapping("removeMistake")
    public String removeMistake(
            @RequestParam("userId") int userId,
            @RequestParam("questionId") int questionId
    ) {

        try {
            umi.removeMistake(userId, questionId);
        } catch (Exception e) {
            return ResultEntity.Fail(-1, "移除错题失败");
        }

        return ResultEntity.Success(1, "移除错题成功");
    }

    /**
     * 根据用户ID和科目ID获取错题
     * 如果不给出subid,那么就返回所有的题目
     * return JSON
     */
    @GetMapping("getMistakeByUserIdAndSubjectId")
    public List<UserMistake> getMistakeByUserIdAndSubjectId(
            @RequestParam("userId") Integer userId,
            @RequestParam("subjectId") Integer subjectId
    ) {
        List<UserMistake> res = new ArrayList<>();
        List<UserMistake> tmp;

        if (subjectId == -1) {
             tmp = umi.getMistakesByUserId(userId);
            for (UserMistake t : tmp) {
                Question question = qsi.getQuestionById(t.getQuestionId());
                t.setQuestion(question);
                res.add(t);
            }
            return res;
        }

        tmp = umi.getMistakeByUserIdAndSubjectId(userId, subjectId);
        for (UserMistake t : tmp) {
            Question question = qsi.getQuestionById(t.getQuestionId());
            t.setQuestion(question);
            res.add(t);
        }

        return res;
    }

    // 添加试卷
    @PostMapping("insertExamPaper")
    public String addExamPaper(@RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime,
                               @RequestParam("examType") String examType, @RequestParam("grade") int grade,
                               @RequestParam("name") String name, @RequestParam("subjectId") int subjectId,
                               @RequestParam("totalScore") int totalScore, @RequestParam("teacherId") int teacherId) {
        try {
            examPaperService.insertExamPaper(startTime, endTime, examType, grade, name, subjectId, totalScore, teacherId);
        } catch (Exception e) {
            ColorChange.Red("Fuck: " + e);
            return ResultEntity.Fail(-1, "新建试卷失败");
        }

        return ResultEntity.Success(1, "新建试卷成功");
    }

    // 删除试卷
    @DeleteMapping("removeExamPaperById")
    public String removeExamPaperById(@RequestParam("examPaperId") int examPaperId) {
        try {
            examPaperService.removeExamPaperById(examPaperId);
        } catch (Exception e) {
            ColorChange.Red("Fuck: " + e);
            return ResultEntity.Fail(-1, "删除试卷失败");
        }
        return ResultEntity.Success(1, "删除试卷成功");
    }

    // 根据id返回试卷
    @GetMapping("getExamPaperById")
    public ExamPaper getExamPaperById(@RequestParam("examPaperId") int examPaperId) {
//        return examPaperService.getExamPaperById(examPaperId);
        try {
            return examPaperService.getExamPaperById(examPaperId);
        } catch (Exception e) {
            ColorChange.Red("Fuck: " + e);
            return null;
        }
    }

    // 修改试卷
    @PutMapping("updateExamPaper")
    public String updateExamPaper(
            @RequestParam("examPaperId") int examPaperId,
            @RequestParam("name") String name,
            @RequestParam("examType") String examType,
            @RequestParam("grade") int grade,
            @RequestParam("subjectId") int subjectId,
            @RequestParam("totalScore") int totalScore,
            @RequestParam("startTime") String startTime,
            @RequestParam("endTime") String endTime) {
        if (examPaperService.getExamPaperById(examPaperId) == null) return ResultEntity.Fail(-1, "八嘎");
        examPaperService.updateExamPaper(examPaperId, name, examType, grade, subjectId, totalScore, startTime, endTime);
        return "哟西";
    }

    // 查询试卷(根据年级，科目id)
    @GetMapping("findExamPapersByGradeAndSubject")
    public List<ExamPaper> findExamPapersByGradeAndSubject(
            @RequestParam("grade") int grade,
            @RequestParam("subjectId") int subjectId) {
        return examPaperService.findExamPapersByGradeAndSubject(grade, subjectId);
    }

    // 给学生发布试卷
    @PostMapping("assignExamPaperToStudent")
    public String assignExamPaperToStudent(
            @RequestParam("studentId") int studentId,
            @RequestParam("examPaperId") int examPaperId) {
        try {
            examPaperService.assignExamPaperToStudent(studentId, examPaperId);
        } catch (Exception e) {
            ColorChange.Red("Fuck: " + e);
            return ResultEntity.Fail(-1, "发布失败");
        }
        return ResultEntity.Success(1, "发布成功");
    }

    // 展示题目(根据题目顺序排序)
    @GetMapping("listQuestionsByExamPaperId")
    public List<Question> listQuestionsByExamPaperId(@RequestParam("examPaperId") int examPaperId) {
        return examPaperService.listQuestionsByExamPaperId(examPaperId);
    }

    @PostMapping("insertQuestion")
    public String insertQuestion(int examPaperId, int questionId, int order) {
        try {
            examPaperService.insertQuestion(examPaperId, questionId, order);
        } catch (Exception e) {
            ColorChange.Red("Fuck: " + e);
            return ResultEntity.Fail(-1, "插入题目失败");
        }
        return ResultEntity.Success(1, "插入题目成功");
    }

    @GetMapping("psychologicalTest")
    public Object psychologicalTest(Integer count) {
        try {
            return qsi.psychologicalTest(count);
        } catch (Exception e) {
            return ResultEntity.Fail(-1, "获取失败");
        }
    }

    @GetMapping("getAllWfsQuestion")
    public List<WfsQuestion> getWfs(String exam_id){
        int eid = Integer.parseInt(exam_id.split("lib_")[1]);
        ExamPaper examPaper = examPaperService.getExamPaperById(eid);
        return examPaper.toWfs();
    }

    @GetMapping("getExamPapersBySubjectId")
    public List<Paper> getExamPapersBySubjectId(@RequestParam Integer subjectId){
         try{
             return examPaperService.getExamPapersBySubjectId(subjectId);
         }catch (Exception e){
             return null;
         }
    }

}
